import 'package:cunyutech_flutter_ui/src/dialog/main.dart';
import 'package:flutter/widgets.dart';
import 'package:move_to_background/move_to_background.dart';

//上次点击时间
DateTime _lastPressedAt;

class ClickTwiceBackToHome extends StatelessWidget {
  const ClickTwiceBackToHome({
    Key key, 
    this.child, 
    this.duration = const Duration(seconds: 2)
  }) : super(key: key);
  final Widget child;
  final Duration duration;
  
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_lastPressedAt == null || DateTime.now().difference(_lastPressedAt) > duration) {
          // 两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          showToast(msg: '再按一次返回桌面');
          return false;
        } else {
          _lastPressedAt = null;
          MoveToBackground.moveTaskToBack();
          return false;
        }
      },
      child: child,
    );
  }
}